import React, { createRef, memo, useEffect, useState } from "react";
import { IObject, Modal, Spin } from "@cscec/udp-ui";

const iframeStyle: React.CSSProperties = {
  width: "100%",
  border: 0,
  overflow: "hidden",
};

interface IIndicatorCenterProps {
  data: IObject; // 用于传输传给iframe组件的数据
  isEdit?: boolean;
}

const IREAME_HREF = "/MetricsCards/list";

const ACCEPT_KEY = "indicator_center_card_child";
const SEND_KEY = "indicator_center_card";
const HEIGHT = 100;

/**
 * 指标中心iframe方式
 * iframe使用postMessage通信
 */
export default memo((props: IIndicatorCenterProps) => {
  const { data, isEdit } = props;
  // 建立通信
  const [communication, setCommunication] = useState(0);
  const iframeRef: any = createRef();
  const { origin, pathname } = location;

  const iframeSrc = origin.includes("localhost")
    ? `${origin}${pathname}#${IREAME_HREF}`
    : `${origin}${pathname}#/sub/metrics${IREAME_HREF}`;

  // 给子组件传递信息
  const sendMsgToChild = (data: any) => {
    // if (!iframeRef.current) return;
    iframeRef.current.contentWindow.postMessage(
      {
        type: SEND_KEY, // 约定的通信key
        data: {
          ...data,
          isEdit,
        },
        href: location.href,
      },
      // 通信的url
      // 指定哪些窗口能接收到消息事件，其值可以是 *（表示无限制）或者一个 URI（注意指定URI不支持跨域，会报错，而*号支持跨域)
      iframeSrc
    );
  };

  // 子组件传递给父组件的信息
  function handleConsole(event: any) {
    const { type: eventType, height } = event.data;
    // 只有约定的key，才执行函数executeFunction
    // 防止其他message污染
    if ([ACCEPT_KEY].includes(eventType)) {
      setCommunication(height);
    }
  }

  // message监听
  useEffect(() => {
    window.addEventListener("message", handleConsole);
    return () => window.removeEventListener("message", handleConsole);
  }, []);

  // 数据源发生改变通知到子组件
  // 首次收到子组件的height通知，传递默认数据源
  useEffect(() => {
    sendMsgToChild(data);
  }, [JSON.stringify(data), communication]);

  return (
    <div
      style={{
        height: communication || HEIGHT,
        marginBottom: "var(--inner-margin, 16px)",
        background: "#fff",
        overflow: "hidden",
      }}
    >
      <Modal open={false} />
      <div
        style={{
          height: communication ? 0 : HEIGHT * 2,
          background: "#fff",
          textAlign: "center",
          paddingTop: communication ? 0 : 30,
        }}
      >
        <Spin spinning={!communication} />
      </div>
      <iframe
        // 可以是指定的地址，同源下路由拼接即可
        src={iframeSrc}
        width={"100%"}
        height={"100%"}
        style={iframeStyle}
        ref={iframeRef}
      />
    </div>
  );
});
